from django.contrib.auth.backends import ModelBackend
import re
from meiduo_mall.meiduo_mall.apps.users.models import User

class MeiduoModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):

        if request is None:
            try:
                user = User.objects.get(username=username, is_staff=True)
            except:
                return None
            if user.check_password(password):
                return user
        else:
            try:
                # if re.match(r'^1[3-9]\d{9}$', username):
                #     user = User.objects.get(mobile=username)
                # else:
                #     user = User.objects.get(username=username)
                user = User.objects.get(username=username)
            except:
                try:
                    user = User.objects.get(mobile=username)
                except:
                    return None
        
        if user.check_password(password):
            return user
        else:
            return None
